package com.hellenic.dao;

import java.util.ArrayList;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.hellenic.beans.ProprieteBean;

public class ProprieteDao implements ProprieteDaoInt {

    private SessionFactory sessionF;

    public ProprieteDao( SessionFactory sessionF ) {
        this.sessionF = sessionF;
        System.out.println( "Message : Instanciation d'un objet ProprieteDao" );
    }

    /**
     * Permet la récupération d'une propriete
     */
    @Override
    public ProprieteBean get( String ref ) throws DaoException {
        String hql = "FROM com.hellenic.beans.ProprieteBean propriete WHERE propriete.ref = '" + ref + "'";
        System.out.println( "HQL : " + hql );
        Session sess = null;
        ProprieteBean unePropriete = null;

        try {
            sess = sessionF.openSession();
            Query query = sess.createQuery( hql );
            unePropriete = (ProprieteBean) query.list().get( 0 );
        } catch ( DaoException e ) {
            System.out.println( "ERREUR : execution get() dans ProprieteDAO " );
        } finally {
            sess.close();
        }
        return unePropriete;
    }

    /**
     * Permet la récupération de n propriete
     */
    @SuppressWarnings( "unchecked" )
    @Override
    public ArrayList<ProprieteBean> linstingPropriete( int nb ) throws DaoException {
        String hql = "FROM com.hellenic.beans.ProprieteBean";
        ArrayList<ProprieteBean> result = null;
        Session sess = null;

        try {
            // ouverture session hibernate
            sess = sessionF.openSession();

            // execution de la requete
            Query query = sess.createQuery( hql );

            // selection de nb propriete
            query.setMaxResults( nb );

            // stockage dans un arrayList
            result = (ArrayList<ProprieteBean>) query.list();

        } catch ( DaoException ex ) {
            System.out.println( "Erreur : execution authentification dans ProprieteDao" );
        } finally {
            // libération des resources
            sess.close();
        }
        return result;
    }

    @Override
    public ArrayList<ProprieteBean> linstingPropriete() throws DaoException {
        // TODO Auto-generated method stub
        return null;
    }
}
